from django.urls import reverse

from django.contrib.auth import login, authenticate
from django.http import HttpResponsePermanentRedirect
from django.shortcuts import render,redirect
from django.views import View
from django.http import HttpResponse, JsonResponse
from operation.models import UserMessage
from operation.models import UserCourse
from courses.models import Course
from operation.models import UserFavorite
from organization.models import CourseOrg
from organization.models import Teacher
from users.models import UserProfile, Banner
from users.forms import UserInfoForm
from users.forms import UploadImageForm
from users.forms import RegisterForm, LoginForm
from users.forms import ForgetForm
from users.models import EmailVerifyRecord
from users.utils import send_register_email
from users.forms import ModifyPwdForm


# 7.用户消息
class MyMessageView(View):
    def get(self, request):
        user_id = request.user.id
        messages = UserMessage.objects.filter(user=user_id)
        # print(messages)
        # print(type(messages))
        return render(request, 'usercenter-message.html', {
            'messages': messages
        })


# 6.公开课程
class MyFavCourseView(View):
    def get(self, request):
        course_list = []

        user = request.user

        user_favs = UserFavorite.objects.filter(user=user)

        for user_fav in user_favs:
            if user_fav.fav_type == 1:

                courses = Course.objects.filter(id=user_fav.fav_id)
                for course in courses:
                    course_list.append({
                        'course_id': course.id,
                        'course': course
                    })

        return render(request, 'usercenter-fav-course.html', {
            'course_list': course_list
        })


# 5.授课教师
class MyFavTeacherView(View):
    def get(self, request):

        teacher_list = []

        user = request.user

        user_favs = UserFavorite.objects.filter(user=user)

        for user_fav in user_favs:
            if user_fav.fav_type == 3:

                teachers = Teacher.objects.filter(id=user_fav.fav_id)
                for teacher in teachers:
                    teacher_list.append({
                        'teacher_id': teacher.id,
                        'teacher': teacher
                    })

        return render(request, 'usercenter-fav-teacher.html', {
            'teacher_list': teacher_list
        })


# 4.课程学校
class MyFavOrgView(View):
    def get(self, request):
        org_list = []

        user = request.user

        user_favs = UserFavorite.objects.filter(user=user)

        for user_fav in user_favs:
            if user_fav.fav_type == 2:

                orgs = CourseOrg.objects.filter(id=user_fav.fav_id)
                for org in orgs:
                    org_list.append({
                        'org_id': org.id,
                        'org': org
                    })

        return render(request, 'usercenter-fav-org.html', {
            'org_list': org_list,
        })
        # return HttpResponse('ok')


# 3.用户课程
class MyCourseView(View):
    def get(self, request):
        user = request.user
        user_courses = UserCourse.objects.filter(user=user)

        # print(user_courses)
        # print(type(user_courses))
        return render(request, 'usercenter-mycourse.html', {
            'user_courses': user_courses
        })
        # return HttpResponse('ok')


# 2.点击修改图片修改头像
class ImageUploadView(View):
    def post(self, request):

        user = request.user
        image_from = UploadImageForm(request.POST, request.FILES)
        # print(image_from)
        res = image_from.is_valid()
        if res:
            image = image_from.cleaned_data['image']
            try:
                user.image = image
                user.save()
            except:
                return JsonResponse({"status": "error", 'msg': '头像修改失败'})
            return JsonResponse({"status": "success", 'msg': '头像修改成功'})


# 1.用户中心：获取信息/修改信息
class UserInfoView(View):
    # 获取当前登录用户信息
    def get(self, request):

        return render(request, 'usercenter-info.html')
    # 修改当前登录用户信息
    def post(self, request):
        data = request.POST
        userinfo_from = UserInfoForm(data)
        # 验证表单
        res = userinfo_from.is_valid()
        if res:
            nick_name = userinfo_from.cleaned_data['nick_name']
            birthday = userinfo_from.cleaned_data['birthday']
            gender = userinfo_from.cleaned_data['gender']
            address = userinfo_from.cleaned_data['address']
            mobile = userinfo_from.cleaned_data['mobile']
            try:
                user = request.user
                user.nick_name = nick_name
                user.birthday = birthday
                user.gender = gender
                user.address = address
                user.mobile = mobile
                user.save()
            except:
                # 验证失败返回表单对象，在模板中渲染错误原因
                return JsonResponse({"status": "error"})
            # 验证成功则保存数据
            return JsonResponse({"status": "success"})
        return JsonResponse({"status": "error"})


# 首页页面
class IndexView(View):
    # 首页显示
    def get(self, request):
        print("1")
        all_banners = Banner.objects.all()
        banner_courses = Course.objects.all()
        course_orgs = CourseOrg.objects.all()
        courses = Course.objects.all()
        return render(request, 'index.html', {
            'all_banners': all_banners,
            'courses': courses,
            'banner_courses': banner_courses,
            'course_orgs': course_orgs,
            # "MEDIA_URL": '/media/'
        })


class LoginView(View):
    # 获取登录页面
    def get(self, request):
        return render(request, 'login.html')

    def post(self, request):
        data = request.POST
        login_form = LoginForm(data)
        res = login_form.is_valid()
        if res:
            sername = login_form.cleaned_data['username']
            password = login_form.cleaned_data['password']

            user = authenticate(username=sername, password=password)
            if user:
                # 保持登录状态
                login(request, user)
                # 登入成功
                return redirect(reverse('users:index'))

        # 登录失败：
        return render(request, 'login.html', {'form_errors': login_form.errors})


# 用户注册
class RegisterView(View):
    # １．展示注册页面
    def get(self, request):
        register_form = RegisterForm()
        return render(request, 'register.html', {'register_form': register_form})

    def post(self, request):

        data = RegisterForm(request.POST)
        # 生成表单对象
        register_form = RegisterForm(data)
        # 验证表单
        res = data.is_valid()
        # 可以通过error属性获取验证失败的原因
        error = data.errors

        if res:
            email = data.cleaned_data['email']
            password = data.cleaned_data['password']

            # 3.注册用户数据
            try:
                user = UserProfile.objects.create_user(
                    username=email,
                    password=password,
                )

                login(request, user)

            except Exception as e:
                return render(request, 'register.html', {'register_form': register_form})

        # username = UserProfile.objects.filter(user=user).get('username')
        # response = HttpResponsePermanentRedirect(reverse('users:index'))
        # response.set_cookie('username', username)

        return HttpResponsePermanentRedirect(reverse('users:index'))


# 1 忘记密码

class ForgetPwdView(View):
    # 显示忘记密码页面
    def get(self, request, ):
        forget_form = ForgetForm()
        return render(request, 'forgetpwd.html', {'forget_form': forget_form})

    # 点击提交
    def post(self, request):

        forget_form = ForgetForm(request.POST)
        if forget_form.is_valid():
            email = request.POST.get('email')

            send_register_email(email)

            return render(request, 'send_success.html')
        else:
            return render(request, 'forgetpwd.html', {'forget_form': forget_form})


# 校验获取修改密码页面
class ResetView(View):
    def get(self, request, active_code):

        record = EmailVerifyRecord.objects.filter(code=active_code)
        print(record)
        try:
            for i in record:
                email = i.email
                is_register = UserProfile.objects.filter(email=email)
                if is_register:
                    return render(request, 'password_reset.html', {'email': email})
        except:
            return render(request, 'active_fail.html')
        return render(request, 'password_reset.html', {'email': email})



# 提交新密码
class ModifyView(View):
    def post(self,request):
        # 获取用户对象
        # email = request.GET.get('token')
        # user = UserProfile.objects.get(email=email)
        # return redirect(reverse('index'))
        user = request.user
        # 1、获取前端传递的表单数据
        data = request.POST
        # 2、生成表单
        modifypwd_form = ModifyPwdForm(data)
        # 2、验证表单数据
        res = modifypwd_form.is_valid()  # 验证成功返回True，验证失败返回False
        print(res)
        if res:
            passwordtwo = modifypwd_form.cleaned_data
            # 如果用户两次输入的密码相等:
            if passwordtwo['password1'] == passwordtwo['password2']:
                # 存入数据库
                try:
                    return redirect(reverse('users:index'))

                    # print(user)
                    # a= UserProfile.objects.get('password')
                    # print(a)
                    # user.set_password(passwordtwo['password1'])
                    # user.save()

                except Exception as e:

                    return render(request, 'active_fail.html')
                login(request,user)
                return redirect(reverse('users:index'))
            return render(request, 'active_fail.html')
        return render(request, 'active_fail.html')
